import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import { appConfig } from '../app.config';
import response from '../common/response';
import business from '../common/business';

interface requestData {
    timeStamp: number,
    sign: string,
    data: any
}

@Injectable()
export class DecodeMiddleware implements NestMiddleware {
    use(req: Request, res: Response, next: Function) {
        business.executeStatement(async () => {
            if (req.method.toUpperCase() === 'GET') {
                return next();
            }

            let data: requestData = req.body;
            if (data.sign && data.timeStamp) {
                let now = business.getNow();
  
                if (!data.timeStamp || typeof data.timeStamp !== 'number') {
                    return res.json(response.errorDetail(`timeStamp不正确或不存在`));
                }
                if (now - data.timeStamp > appConfig.serverTimeStamp || now < data.timeStamp) {
                    return res.json(response.errorDetail(`timeStamp已失效`));
                }
                if (!data.sign || typeof data.sign !== 'string') {
                    return res.json(response.errorDetail(`sign不正确或不存在`));
                }
                if (business.makeSign(data, appConfig.dataEncryptKey) !== data.sign.toUpperCase()) {
                    return res.json(response.errorDataSign(`sign签名校验失败`));
                }

                req.body = data.data;
                return next();
            }

            return next();
        }, err => {
            return res.json(response.error(err.message));
        });
    }
}
